<template>
  <el-drawer v-model="drawer" :close-on-click-modal="false" :direction="direction">
    <template #header>
      <h4>添加订单</h4>
    </template>
    <template #default>
      <el-form ref="ruleFormRef" style="max-width: 600px" :model="ruleForm" :rules="rules" label-width="auto" label-position="top">
        <el-form-item label="用户ID" prop="userId">
          <el-input v-model="ruleForm.userId" placeholder="请输入用户ID"/>
        </el-form-item>
        <el-form-item label="酒店名称" prop="hotelName">
          <el-select v-model="ruleForm.hotelName" placeholder="请选择酒店" style="width: 100%" @change="loadRoomTypes">
            <el-option v-for="item in hotelList" :key="item.hotelName" :label="item.hotelName" :value="item.hotelName"/>
          </el-select>
        </el-form-item>
        <el-form-item label="房型" prop="roomType">
          <el-select v-model="ruleForm.roomType" placeholder="请选择房型" style="width: 100%" @change="updateRoomPrice">
            <el-option v-for="item in roomList" :key="item.roomType" :label="item.roomType" :value="item.roomType"/>
          </el-select>
        </el-form-item>
        <el-form-item label="价格" v-if="roomPrice">
          <el-input v-model="roomPrice" disabled>
            <template #append>¥</template>
          </el-input>
        </el-form-item>
      </el-form>
    </template>
    <template #footer>
      <div style="flex: auto">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="submitForm">确认</el-button>
      </div>
    </template>
  </el-drawer>
</template>
<script setup lang="ts">
import { ref, reactive } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import { ElMessage } from 'element-plus'
import { createOrder } from '@/api/order'
import { getHotelList } from '@/api/hotel'
import { getRoomList } from '@/api/room'

const emit = defineEmits(['refresh'])

interface RuleForm {
  userId: string
  hotelName: string
  roomType: string
}

const ruleFormRef = ref<FormInstance>()
const ruleForm = reactive<RuleForm>({
  userId: '',
  hotelName: '',
  roomType: ''
})
const hotelList = ref([])
const roomList = ref([])
const roomPrice = ref('')

const drawer = ref(false)
const direction = ref<'rtl' | 'ltr' | 'ttb' | 'btt'>('rtl')

const rules = reactive<FormRules<RuleForm>>({
  userId: [{ required: true, message: '请输入用户ID', trigger: 'blur' }],
  hotelName: [{ required: true, message: '请选择酒店', trigger: 'change' }],
  roomType: [{ required: true, message: '请选择房型', trigger: 'change' }]
})

// 根据酒店名称加载房型列表
const loadRoomTypes = (hotelName: string) => {
  if (hotelName) {
    // 重置房型和价格
    ruleForm.roomType = '';
    roomPrice.value = '';
    
    // 根据酒店名称获取房型列表
    getRoomList({}).then(res => {
      console.log('获取房间列表响应:', res);
      const result = res.data;
      if (result && result.code === 200 && result.data) {
        // 筛选当前酒店的房型
        roomList.value = result.data.filter((room: any) => room.hotelName === hotelName);
      } else {
        roomList.value = [];
        ElMessage.warning('获取房型列表失败');
      }
    }).catch(error => {
      console.error('获取房型列表错误:', error);
      ElMessage.error('网络错误，获取房型列表失败');
    });
  } else {
    roomList.value = []
    roomPrice.value = ''
  }
}

// 更新选中房间的价格
const updateRoomPrice = (roomType: string) => {
  if (roomType && ruleForm.hotelName) {
    const selectedRoom = roomList.value.find((room: any) => 
      room.roomType === roomType && room.hotelName === ruleForm.hotelName
    );
    
    if (selectedRoom && selectedRoom.price) {
      roomPrice.value = selectedRoom.price;
    } else {
      roomPrice.value = '';
    }
  } else {
    roomPrice.value = '';
  }
}

const submitForm = () => {
  ruleFormRef.value.validate((valid) => {
    if (valid) {
      // 构建订单数据
      const formData = {
        userId: ruleForm.userId,
        hotelName: ruleForm.hotelName,
        roomType: ruleForm.roomType,
        amount: roomPrice.value // 添加价格字段
      };
      
      console.log('提交新增订单数据:', formData);
      
      createOrder(formData).then(res => {
        console.log('新增订单响应:', res);
        
        const result = res.data;
        if (result && result.code === 200) {
          ElMessage.success('添加成功')
          handleClose()
          emit('refresh')
        } else {
          ElMessage.error(result?.msg || '添加失败')
        }
      }).catch(error => {
        console.error('添加订单错误:', error);
        ElMessage.error('网络错误，添加订单失败');
      });
    }
  })
}
const handleClose = () => {
  drawer.value = false
}
const open = () => {
  drawer.value = true;
  
  // 重置表单
  ruleForm.userId = '';
  ruleForm.hotelName = '';
  ruleForm.roomType = '';
  roomPrice.value = '';
  
  // 获取酒店列表
  getHotelList({}).then(res => {
    console.log('获取酒店列表响应:', res);
    const result = res.data;
    if (result && result.code === 200 && result.data) {
      hotelList.value = result.data;
    } else {
      ElMessage.warning('获取酒店列表失败');
    }
  }).catch(error => {
    console.error('获取酒店列表错误:', error);
    ElMessage.error('网络错误，获取酒店列表失败');
  });
}
defineExpose({ open })
</script>
